import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../store/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue')
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/Register.vue')
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('../views/Layout.vue'),
      redirect: '/home/hotels',
      children: [
        {
          path: 'hotels',
          name: 'hotels',
          component: () => import('../views/hotels/index.vue')
        },
        {
          path: 'profile',
          name: 'profile',
          component: () => import('../views/profile/index.vue')
        }
      ]
    },
    {
      path: '/hotel/:id',
      name: 'hotelDetail',
      component: () => import('../views/hotels/detail.vue')
    },
    {
      path: '/room/:id',
      name: 'roomDetail',
      component: () => import('../views/hotels/room-detail.vue')
    },
    {
      path: '/order/:roomId',
      name: 'createOrder',
      component: () => import('../views/order/create.vue')
    },
    {
      path: '/order/success',
      name: 'orderSuccess',
      component: () => import('../views/order/success.vue')
    },
    {
      path: '/order/detail/:id',
      name: 'orderDetail',
      component: () => import('../views/order/detail.vue')
    },
    {
      path: '/order/list',
      name: 'orderList',
      component: () => import('../views/order/list.vue')
    }
  ]
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 不需要登录的页面
  const publicPages = ['/login', '/register']
  const isPublicPage = publicPages.includes(to.path)
  
  if (!isPublicPage && !token) {
    // 需要登录但无token，跳转到登录页
    next('/login')
  } else if (token) {
    // 有token，检查是否有用户信息
    const userStore = useUserStore()
    
    if (Object.keys(userStore.userInfo).length === 0 && !isPublicPage) {
      // 有token但无用户信息，且不是公开页面，则获取用户信息
      try {
        await userStore.getUserInfoAction()
        next()
      } catch (error) {
        console.error('获取用户信息失败', error)
        userStore.logout() // 信息获取失败，清除token
        next('/login')
      }
    } else {
      // 有token且有用户信息，或者是公开页面
      next()
    }
  } else {
    // 公开页面且无token
    next()
  }
})

export default router 